import Vue from 'vue';
import VueRouter from 'vue-router';
import iView from 'view-design';


import util from '@/libs/util'


import Setting from '@/setting';


import store from '@/store/index';


import BasicLayout from '@/layouts/basic-layout';
import Layout from '@/layouts/basic-layout' //Layout 是架构组件，不在后台返回，在文件里单独引入
import { frameInRoutes } from '@/router/routes';
import { getRoutersData } from '@/api/account'


// 路由数据
import routes from './routes';


Vue.use(VueRouter);


// 导出路由 在 main.js 里使用
const router = new VueRouter({
    routes,
    mode: Setting.routerMode,
    base: Setting.routerBase
});


var getRouter //用来获取后台拿到的路由


/**
* 路由拦截
* 权限验证
*/
router.beforeEach(async (to, from, next) => {
    if (Setting.showProgressBar) iView.LoadingBar.start();
    // 判断是否需要登录才可以进入
    let _this = router.app
    // console.log('进入了 each', to,from)
    // debugger
    if (to.matched.some(_ => _.meta.auth)) { // 刷新 to.matched 为空了
        // console.log("进入了第一层判断")
        // 这里依据 token 判断是否登录，可视情况修改
        // const token = util.cookies.get('token');
        const token = localStorage.token ? localStorage.token : sessionStorage.token;
        /* console.log('token',token) */
        if (token && token !== 'undefined') {
            const userInfo = await store.dispatch('admin/db/get', {
                dbName: 'sys',
                path: 'user.info',
                defaultValue: {},
                user: true
            }, { root: true });
            /* if(userInfo.access && userInfo.access.some(item=>item==="admin")){} */
            if(userInfo.rolename === "超级管理员") {
                console.log(userInfo.rolename)
                if (!getRouter) {//不加这个判断，路由会陷入死循环
                    if (!getObjArr('router')) {
                        getRoutersData().then(res=> {
                            getRouter = res.data.data.routersData//后台拿到路由
                            // saveObjArr('router', getRouter) //存储路由到localStorage
                
                            routerGo(to, next)//执行路由跳转方法
                        }).catch(err=> {
                        })
                    } else {//从localStorage拿到了路由
                        console.log('从localStorage拿到了路由')
                        getRouter = getObjArr('router')//拿到路由
                        routerGo(to, next)
                    }
                } else {
                    next()
                }
            }
            // console.log("进入了第2层判断")
            // next()
        } else {
            // 没有登录的时候跳转到登录界面
            // 携带上登陆成功之后需要跳转的页面完整路径
            next({
                name: 'login',
                query: {
                    redirect: to.fullPath
                }
            });
        }
    } else {
        // 不需要身份校验 直接通过
        // next();
        console.log(to.name)
        if(to.name === "login") {
            next();
        } else {
            next({name: 'index'});
            // if (!getRouter) {//不加这个判断，路由会陷入死循环
            if (!getObjArr('router')) {
                getRouter = routersData//本地拿路由，后端出接口后转为后端请求
                saveObjArr('router', getRouter) //存储路由到localStorage
                routerGo(to, next)//执行路由跳转方法
                /* getRoutersData().then(res=> {
                    
                }).catch(err=> {
                }) */
            } else {//从localStorage拿到了路由
                console.log('从localStorage拿到了路由')
                getRouter = getObjArr('router')//拿到路由
                routerGo(to, next)
            }
            /* } else {
                next()
            } */
        }
    }
});


router.afterEach(to => {
    if (Setting.showProgressBar) iView.LoadingBar.finish();
    // 多页控制 打开新的页面
    store.dispatch('admin/page/open', to);
    // 更改标题
    util.title({
        title: to.meta.title
    });
    // 返回页面顶端
    window.scrollTo(0, 0);
});


export default router;


function routerGo(to, next) {
    console.log(getRouter)
    getRouter = filterAsyncRouter(getRouter) //过滤路由
    console.log(getRouter)
    router.addRoutes(getRouter.concat([{
        path: '*',
        name: '404',
        meta: {
            title: '404'
        },
        component: () => import('@/pages/system/error/404')
    }])) //动态添加路由
    global.antRouter = getRouter //将路由数据传递给全局变量，做侧边栏菜单渲染工作
    next({ ...to, replace: true })
}
  
function saveObjArr(name, data) { //localStorage 存储数组对象的方法
    localStorage.setItem(name, JSON.stringify(data))
}
  
function getObjArr(name) { //localStorage 获取数组对象的方法
    return JSON.parse(window.localStorage.getItem(name));
}


const _import = require('./_import_' + process.env.NODE_ENV)//获取组件的方法




function filterAsyncRouter(asyncRouterMap) { //遍历后台传来的路由字符串，转换为组件对象
    const accessedRouters = asyncRouterMap.filter(route => {
        if (route.component) {
            if (route.component === 'Layout') {//Layout组件特殊处理
                route.component = Layout
            } else {
                route.component = _import(route.component)
            }
        }
        if (route.children && route.children.length) {
            route.children = filterAsyncRouter(route.children)
        }
        return true
    })


    return accessedRouters
}

const routersData = [
    {
        path: '/',
        component: 'Layout',
        children: [
            {
                path: 'tabs/examinee',
                name: 'examinee',
                meta: {
                    title: '管理员管理',
                    auth: ['admin'],
                    closable: false
                },
                component: ('tabs/examinee/index')
            },
            {
                path: 'tabs/examineeInfo',
                name: 'examineeInfo',
                meta: {
                    title: '考生信息',
                    auth: ['admin'],
                    closable: false
                },
                component: ('tabs/examinee/component/examineeInfo')
            },
            {
                path: 'tabs/examiner',
                name: 'examiner',
                meta: {
                    title: '考务人员管理',
                    auth: ['admin'],
                    closable: false
                },
                component: ('tabs/examiner/index')
            },
            {
                path: 'tabs/examinerInfo',
                name: 'examinerInfo',
                meta: {
                    title: '考务人员信息',
                    auth: ['admin'],
                    closable: false
                },
                component: ('tabs/examiner/component/examinerInfo')
            },
            {
                path: 'tabs/',
                redirect: {
                    name: 'project'
                },
                component: ('tabs/common/viewMiddleware'),
                children: [
                    {
                        path: 'project',
                        name: 'project',
                        meta: {
                            title: '考务项目管理',
                            auth: ['admin'],
                            closable: false
                        },
                        component: ('tabs/examinationProject/index')
                    },
                    {
                        path: 'project/setnotice',
                        name: 'setnotice',
                        meta: {
                            title: '公告设置',
                            auth: ['admin'],
                            closable: false
                        },
                        component: ('tabs/examinationProject/project/setnotice')
                    },
                    {
                        path: 'project/setProjectFlow',
                        name: 'setProjectFlow',
                        meta: {
                            title: '项目流程设置',
                            auth: ['admin'],
                            closable: false
                        },
                        component: ('tabs/examinationProject/project/setProjectFlow')
                    },
                    {
                        path: 'project/setstation',
                        name: 'setstation',
                        meta: {
                            title: '岗位设置',
                            auth: ['admin'],
                            closable: false
                        },
                        component: ('tabs/examinationProject/project/setstation')
                    },
                    {
                        path: 'project/applyCheck',
                        name: 'applyCheck',
                        meta: {
                            title: '报名审查',
                            auth: ['admin'],
                            closable: false
                        },
                        component: ('tabs/examinationProject/project/applyCheck')
                    },
                    {
                        path: 'project/admissionTicket',
                        name: 'admissionTicket',
                        meta: {
                            title: '准考证',
                            auth: ['admin'],
                            closable: false
                        },
                        component: ('tabs/examinationProject/project/admissionTicket')
                    },
                    {
                        path: 'project/resultPublish',
                        name: 'resultPublish',
                        meta: {
                            title: '成绩公布',
                            auth: ['admin'],
                            closable: false
                        },
                        component: ('tabs/examinationProject/project/resultPublish')
                    },
                    {
                        path: 'project/interviewSign',
                        name: 'interviewSign',
                        meta: {
                            title: '面试签到',
                            auth: ['admin'],
                            closable: false
                        },
                        component: ('tabs/examinationProject/project/interviewSign')
                    },
                    {
                        path: 'project/Q_Asession',
                        name: 'Q_Asession',
                        meta: {
                            title: '考生问答',
                            auth: ['admin'],
                            closable: false
                        },
                        component: ('tabs/examinationProject/project/Q_Asession')
                    }
                ]
            }
        ]
    }
]